// pages/me/me.js
import { getUserInfo, userLogin, signEveryDate, getUserTaskList, receiveTaskReward,getShareSetting } from '../../utils/service.js'
var config = require('../../config/config');
var enum_type = require('../../utils/enum');
var util = require('../../utils/util');
var common = require('../../utils/common');

var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    userTaskList: [],
    signStatus:false
  },
  addxiao: function () {
    if (!this.data.userInfo) {
      this.getWxUser(this.realAddxiao, null);
    } else {
      this.realAddxiao();
    }
  },
  realAddxiao:function(){
    wx.navigateTo({
      url: '../entry/entry',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    //获取用户任务列表
    this.getUserTaskList();

    this.getShareInfo();
    this.getNavlist();

  },getNavlist: function () {

    let that = this;
    common.getNavlist(function (res) {
      var page = util.getCurrentPageUrl();
      for (var item in res) {

        if (res[item].pageUrl == page) {
          res[item].isSelect = true;
          break;
        }
      }
      that.setData({
        navs: res
      })
    });
  },
  jumpPage: function (event) {
    common.jumpPage(event);
  },
  getShareInfo: function () {
    var that = this;
    var appId = config.appId;
    getShareSetting({
      appid: appId,
      "type": enum_type.pageEnum.ME
    }).then(res => {
      that.setData({
        shareInfo: res
      })

    }).catch(e => {

    })
  },

  //点击获取用户信息
  getWxUser: function (excuteMethod,paramsObj) {
    let that = this;
    // 查看是否授权，获取用户信息
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function (res) {
              that.userLogin(res.userInfo, excuteMethod, paramsObj);
            }
          })
        } else {
          wx.showModal({
            title: '授权失败',
            content: '授权失败，请重新点击授权！',
            showCancel:false
          })
        }
      }
    })

  },

  //用户登录
  userLogin: function (wxUserInfo, excuteMethod, paramsObj) {
    let that = this;
    wx.login({
      success: function (res) {
        userLogin({
          nickName: wxUserInfo.nickName,
          avatarUrl: wxUserInfo.avatarUrl,
          gender: wxUserInfo.gender,
          city: wxUserInfo.city,
          province: wxUserInfo.province,
          country: wxUserInfo.country,
          openId: '',
          appId: config.appId,
          code: res.code
        }).then(res => {
          if (res.loginStatus == true) {
            that.setData({
              userInfo: res.userInfo
            })

            wx.setStorageSync("userInfo", res.userInfo)

            if (excuteMethod instanceof Function) {
              // excuteMethod(paramsObj); //暂时修改为不跳转
            }

            //获取用户任务列表
            that.getUserTaskList();
          }

        }).catch(e => {
          console.log("查询接口异常！" + e);
        });
      }
    })
  },
  //根据openId获取后台用户
  getUserInfo: function (openId) {
    let that = this;
    getUserInfo({
      openId: openId
    }).then(res => {
      if (res.userInfo) {
        that.setData({
          userInfo: res.userInfo
        })
        wx.setStorageSync("userInfo", res.userInfo)
      }

      that.setData({
        signStatus: res.signStatus
      })

      //获取用户任务列表
      that.getUserTaskList();

    }).catch(e => {
      console.log("查询接口异常！" + e)
    })
  },
  /**
   * 每日签到
   */
  signEveryDate: function () {
    if (this.data.signStatus){
      return;
    }

    if (!this.data.userInfo) {
      this.getWxUser(this.realSignEveryDate, null);
    } else {
      this.realSignEveryDate();
    }

  },
  realSignEveryDate:function(){
    let that = this;
    signEveryDate({
      userId: that.data.userInfo.id
    }).then(res => {
      if (res.signStatus == true) {
        wx.showToast({
          title: '签到成功',
        })

        that.getUserInfo(that.data.userInfo.openId)
      } else {
        wx.showToast({
          title: '签到失败，请稍后再试！',
        })
      }
    }).catch(e => {
      console.log(e)
    });
  },

  getUserTaskList: function () {
    var userId;
    let that = this;
    if (that.data.userInfo) {
      userId = that.data.userInfo.id;
    } else {
      userId = -1;
    }
    getUserTaskList({
      userId: userId
    }).then(res => {
      that.setData({
        userTaskList: res.userTaskList
      })


    }).catch(e => {
      console.log(e)
    });


  },
  //领取奖励
  receiveTaskReward: function (e) {
    if (!this.data.userInfo){
      this.getWxUser(this.realReceiveTaskReward,e);
    } else {
      this.realReceiveTaskReward(e);
    }
  },
  //领取奖励
  realReceiveTaskReward:function(e){
    let that = this;
    var userId = that.data.userInfo.id;
    var index = e.currentTarget.dataset.index;
    var userTaskInfo = that.data.userTaskList[index];
    var userTaskId = userTaskInfo.id;

    //已领取直接返回
    if (userTaskInfo.receiveStatus == true) {
      return;
    }

    //如果任务完成度不够直接跳首页
    if (userTaskInfo.completeTaskNums != userTaskInfo.taskNums) {

      //非分享类型的调整到首页
      if (userTaskInfo.id != 3){
        wx.reLaunch({
          url: '../index/index'
        })
      } 
      
    } else {
      receiveTaskReward({
        userId: userId,
        userTaskId: userTaskId
      }).then(res => {
        if (res.receiveStatus == false) {
          wx.showToast({
            title: res.receiveMsg
          })
        } else {
          //获取用户任务列表
          that.getUserTaskList();
          that.getUserInfo(that.data.userInfo.openId)
        }
      }).catch(e => {
        console.log(e)
      });
    }
  },
  //去抽奖
  luckDraw:function(){
    if(!this.data.userInfo){
      this.getWxUser(this.realLuckDraw, null);
    } else {
      this.realLuckDraw();
    }    
  },
  realLuckDraw:function(){
    wx.navigateTo({
      url: '../luckdraw/luckdraw?userId=' + this.data.userInfo.id,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var userInfo = wx.getStorageSync("userInfo");
    if (userInfo) {
      this.getUserInfo(userInfo.openId);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  //页面分享以及右上角分享
  onShareAppMessage: function (e) {

    var shareInfo = this.data.shareInfo;
    if (shareInfo) {
      return {
        title: shareInfo.title,
        imageUrl: shareInfo.imageSrc,
        path: 'pages/index/index?userId=' + this.data.userInfo.id
      }
    } else {
      return {
        path: 'pages/index/index?userId=' + this.data.userInfo.id
      }
    }

  }
})